package top.codef.secure.config.delegates;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.secure.config.interfaces.CerberusHttpSecurityConfig;
import top.codef.secure.config.interfaces.LoginFailedDecorator;
import top.codef.secure.config.interfaces.LoginSuccessDecorator;
import top.codef.secure.handlers.CerberusLoginFailedHandler;
import top.codef.secure.handlers.CerberusLoginSuccessHandler;
import top.codef.secure.properties.CerberusCsrfProperties;
import top.codef.secure.properties.CerberusFormLoginProperties;
import top.codef.secure.properties.CerberusLoginReturnProperties;

@Configuration
@EnableConfigurationProperties({ CerberusFormLoginProperties.class, CerberusLoginReturnProperties.class })
@Order(5)
public class CerberusFormLoginConfig implements CerberusHttpSecurityConfig {

	@Autowired
	private CerberusFormLoginProperties cerberusFormLoginProperties;

	@Autowired
	private ObjectMapper objectMapper;

	private final Log logger = LogFactory.getLog(CerberusFormLoginConfig.class);

	@Autowired(required = false)
	private CerberusCsrfProperties cerberusCsrfProperties;

	@Autowired
	private CerberusLoginReturnProperties cerberusLoginReturnProperties;

	@Autowired
	private LoginSuccessDecorator loginSuccessDecorator;

	@Autowired
	private LoginFailedDecorator loginFailedDecorator;

	@Override
	public void secure(HttpSecurity httpSecurity) throws Exception {
		logger.debug("表单登录设置");
		if (cerberusFormLoginProperties.isEnabled()) {
			CerberusLoginSuccessHandler loginSuccessHandler = new CerberusLoginSuccessHandler(objectMapper,
					cerberusCsrfProperties, cerberusLoginReturnProperties, loginSuccessDecorator);
			CerberusLoginFailedHandler loginFailHandler = new CerberusLoginFailedHandler(objectMapper,
					cerberusLoginReturnProperties, loginFailedDecorator);
			httpSecurity.formLogin(x -> x.usernameParameter(cerberusFormLoginProperties.getParamUsername())
					.passwordParameter(cerberusFormLoginProperties.getParamPwd())
					.loginProcessingUrl(cerberusFormLoginProperties.getLoginPath()).successHandler(loginSuccessHandler)
					.failureHandler(loginFailHandler));
		} else
			httpSecurity.formLogin(x -> x.disable());
	}
}
